package cn.edu.nju.ws.sview.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.URIIDCache;
import cn.edu.nju.ws.sview.util.URIUtil;
import cn.edu.nju.ws.sview.views.Entity;
import cn.edu.nju.ws.sview.views.User;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing.QuadItem;


public class HistoryServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String HISTORY_ENTITY = "entity";
	public static final String HISTORY_COLLECTION = "collection";
	public static final String HISTORY_DATASET = "dataset";
	
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("utf-8");
		String jsonstr = request.getParameter("getHistory");
		if(jsonstr != null){
			String str = URLDecoder.decode(jsonstr, "utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String user = (String) regtJSON.get("user");
			String type = (String) regtJSON.get("type");
			int num = ((Long) regtJSON.get("num")).intValue();
			String lang = (String) regtJSON.get("lang");
			JSONObject result = new JSONObject();
			int userId=-1;
			if(user != null){
				userId = User.getUserIdByName(user);
			}else{
				result.put("status", "Illegal user name");
				response.getWriter().print(result);
				return;
			}
//			System.out.println("user:"+user+"|id:"+userId+"|num:"+num);
			if(type.contentEquals(HISTORY_ENTITY)){ 
				ArrayList<QuadItem> array = EntityBrowsing.getLatestEntityInHistory(userId, num);
				JSONArray elements = new JSONArray();
				for (QuadItem item : array) {
					JSONObject jsob = new JSONObject();
					jsob.put("genre", item.getGenre());
					jsob.put("id", item.getId());
					String name = item.getName();
					if (item.getGenre() == Entity.URI_ENTITY && name.equals("")) {
						if (lang.equals("en")) {
							try {
								name = URIUtil.getLocalname(URIIDCache
										.getInstance().getURI(item.getId()));
							} catch (Throwable e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							continue;
						}
					}
					jsob.put("name", name);
					JSONArray types = new JSONArray();
					ArrayList<Entry<Integer, String>> typeArray = item.getTypes();
					for (Entry<Integer, String> mapItem : typeArray) {
//						System.out.println("type_id"+mapItem.getKey()+"|label:"+mapItem.getValue());
						JSONObject tob = new JSONObject();
						tob.put("label", mapItem.getValue());
						tob.put("type_id", mapItem.getKey());
						types.add(tob);
					}
					jsob.put("type", types);
					elements.add(jsob);
				}
				System.out.println("ehistory:"+elements.toJSONString());
				result.put("elements", elements);
				result.put("status", "ok");
				response.getWriter().print(result);
			} else if(type.contentEquals(HISTORY_COLLECTION)){
				ArrayList<QuadItem> array = EntityBrowsing.getLatestCollectionInHistory(userId, num);
				JSONArray elements = new JSONArray();
				for (QuadItem item : array) {
					JSONObject jsob = new JSONObject();
					jsob.put("genre", item.getGenre());
					jsob.put("id", item.getId());
					String name = item.getName();
					if (item.getGenre() == Entity.URI_ENTITY && name.equals("")) {
						if (lang.equals("en")) {
							try {
								name = URIUtil.getLocalname(URIIDCache
										.getInstance().getURI(item.getId()));
							} catch (Throwable e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							continue;
						}
					}
					jsob.put("name", name);
					JSONArray types = new JSONArray();
					ArrayList<Entry<Integer, String>> typeArray = item.getTypes();
					for (Entry<Integer, String> mapItem : typeArray) {
//						System.out.println("type_id"+mapItem.getKey()+"|label:"+mapItem.getValue());
						JSONObject tob = new JSONObject();
						tob.put("label", mapItem.getValue());
						tob.put("type_id", mapItem.getKey());
						types.add(tob);
					}
					jsob.put("type", types);
					elements.add(jsob);
				}
				System.out.println("chistory:"+elements.toJSONString());
				result.put("elements", elements);
				result.put("status", "ok");
				response.getWriter().print(result);
			} else if(type.contentEquals(HISTORY_DATASET)){

				response.getWriter().print(result);
			} else{
				result.put("status", "Illegal type");
				response.getWriter().print(result);
			}
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		doGet(request, response);
	}

}
